<?php
/**
 * author: yunshu
 * create: 18/2/28
 * description:
 */

namespace app\common\service;

use app\common\model\Order as OrderModel;
use app\common\model\Product;
use app\common\service\Order as OrderService;
use app\library\enum\OrderStatus;
use think\Db;
use think\Exception;
use think\facade\Env;
use think\facade\Log;

require_once Env::get('root_path') . 'extend/wxpay/WxPay.Api.php';

class WxPayCallback extends \WxPayNotify
{
    public function NotifyProcess($data, &$msg)
    {
        if ($data['return_code'] != 'SUCCESS') {
            return false;
        } elseif ($data['result_code'] != 'SUCCESS') {
            return true;   //微信支付失败,不再进行异步通知
        } else {
            Db::startTrans();
            try {
                $order = OrderModel::where('order_no', '=', $data['out_trade_no'])->find();
                if ($order->status == OrderStatus::UN_PAID) {
                    $orderStatus = (new OrderService())->checkOrderStock($order->id);
                    if ($orderStatus['pass']) {
                        $this->updateOrderStatus($order->id, OrderStatus::PAID);
                        $this->reduceProductStock($orderStatus);
                    } else {
                        $this->updateOrderStatus($order->id, OrderStatus::PAID_BUT_OUT_OF);
                    }
                }
                Db::commit();

                return true;
            } catch (Exception $e) {
                Db::rollback();
                Log::error($e);

                return false;
            }
        }
    }

    private function reduceProductStock($orderStatus)
    {
        foreach ($orderStatus as $status) {
            Product::where('id', '=', $status['id'])->setDec('stock', $status['count']);
        }
    }

    private function updateOrderStatus($orderId, $status)
    {
        OrderModel::where('id', '=', $orderId)->update(['status'=>$status]);
    }
}